package com.delta.rafg.core.database.impl;


import java.sql.SQLException;
import java.sql.Statement;

import com.delta.rafg.core.config.ConfigSettings;
import com.delta.rafg.core.database.DataHandlerOptions;
import com.delta.rafg.core.exception.RAFGException;

/**
 * @author RAFG Development Team (D9127520)
 *
 */
public class OracleCacheDataHandlerImpl extends ACacheDataHandler {

    private static final long serialVersionUID = -3903559075235117415L;
    private String driverClassName = "oracle.jdbc.driver.OracleDriver";

    private static final int SCHEMA_MISSING_ERR = 942;

    @Override
    public void initialize(String dataHandlerPropertyIdentifier)  throws RAFGException {
        if (dataHandlerPropertyIdentifier == null) {
            throw new java.lang.IllegalArgumentException("dataHandlerPropertyIdentifier cannot be null");
        }
        dataHandlerOptions = new DataHandlerOptions();
        dataHandlerOptions.setConfigSettings(ConfigSettings.getSingleton());
        dataHandlerOptions.setDataHandlerPropertyIdentifier(dataHandlerPropertyIdentifier);

        initialize(dataHandlerOptions);
    }

    /**
     * Initialize the cache data handler - Oracle Implementation.
     * @param options - DataHandlerOptions for initializing OracleCacheDataHandler
     * <p><b>Optional DataHandlerOptions custom mappings</b>
     * <br>"DataBasePath" - Override default Derby DataBase Path location
     * @throws RAFGException
     */
    @Override
    public void initialize(DataHandlerOptions options) throws RAFGException {
        super.initialize(options);
        if (options == null) {
            options = new DataHandlerOptions();
        }
        if (options.getDriverClassName() == null) {
            options.setDriverClassName(driverClassName);
        }
    }

	@Override
	public boolean isSchemaExistsException(SQLException e) {
		int err = e.getErrorCode();
	    if (err == SCHEMA_MISSING_ERR) {
	    	return true;
	    } else {
	    	return false;
	    }
	}

	@Override
	public boolean checkTableExists(Statement stmt, String cacheTable) {
		boolean tableExists = true;
		try {
			stmt.execute("select * from " + cacheTable + " where rownum=1");
		} catch (ArrayIndexOutOfBoundsException e) {
			//do nothing if I catch this, for some reason Oracle
			//will throw this if the table has any BLOBs in it.
		} catch (SQLException e) {
			//if its because the table doesn't exist, return that the cache has not been created yet.
			if (isSchemaExistsException(e)) {
				tableExists = false;
			}
		}
		return tableExists;
	}
}
